//app.js

const Request = require('./utils/requist.js');

App({

    // Promise to wx
    wxmp: require('./utils/promify.js'),
    
    onLaunch: function () {
        
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

        // 登录
        this.login();

    },
    // util.js
    util: require('./utils/util.js'),
    // api接口地址
    api: require('api.js'),
    // 全局变量
    globalData: {
        userInfo: null,//用户信息
        serviceTypeList: null,//服务类型列表
    },

    // 显示加载层
    showLoading: function (title) {
        if (!title) {
            title = '加载中';
        }
        wx.showLoading({
            title: title,
        })
    },
    // 隐藏加载层
    hideLoading: function () {
        wx.hideLoading();
    },
    // 提示
    showToast: function(msg, icon, callback){
        var object = {title: msg, mask: true};
        if(icon) {
            object.icon = icon;
        } else {
            object.icon = 'none';
        }
        if(typeof callback == 'function') {
            object.complete = callback;
        }
        wx.showToast(object);
    },
    // 模态弹窗
    showModal: function(title, content, showCancel, confirmCallback, cancelCallback, confirmText, cancelText) {
        var object = {
            title: title,
            content: content,
            success: function(res) {
                if(typeof confirmCallback == 'function' && res.confirm) {
                    confirmCallback();
                } else if(typeof cancelCallback == 'function' && res.cancel) {
                    cancelCallback();
                }
            }
        }

        if(confirmText) {
            object.confirmText = confirmText;
        }
        
        if(cancelText) {
            object.cancelText = cancelText;
        }
        
        if(showCancel === false) {
            object.showCancel = false;
        }

        return wx.showModal(object);
    },
    navigateTo: function (page, ms) {
        if (ms) { //传参
            page = page + '?' + ms;
        }
        wx.navigateTo({
            url: page
        })
    },
    navigateBack: function(number) {
        if(!number) {
            number = 1;
        }
        // 非数字，页面路径字符串
        if(isNaN(number)) {
            var n = 0;
            var pages = wx.getCurrentPages();
            for(var i=(pages.length); i > 0; i--) {
                n++;
                if(pages[i-1] == number) {
                    number = n;
                    break;
                }
            }
            if(n == 0) {
                number = 1;
            }
        }
        

        wx.navigateBack({
            delta: number
        })

        
    },
    redirectTo: function (path, ms) {
        if (ms) { //传参
            path = path + '?' + ms;
        }
        wx.redirectTo({
            url: path
        })
    },
    reLaunch: function (page, ms) {
        if (ms) { //传参
            page = page + '?' + ms;
        }
        wx.reLaunch({
            url: page
        })
    },
    switchTab: function(page) {
        wx.switchTab({
            url: page
        })
    },


    /**
     * 有关页面
     * */
    page: {

        home: '/pages/index/index',
        PerfectInformation: "/pages/PerfectInformation/PerfectInformation",
        SingleState: "/pages/SingleState/SingleState",
        Member: "/pages/Member/Member",
        Coupon: "/pages/Coupon/Coupon",
        SetMeal: "/pages/SetMeal/SetMeal",
        setting: "/pages/setting/setting",
        Personal: "/pages/Personal/Personal",
        Calculator: "/pages/Calculator/Calculator",
        message: "/pages/message/message",
        order: "/pages/order/order",
        orderDetail: "/pages/orderDetail/orderDetail",
        Complaint: "/pages/Complaint/Complaint",
        Recommend: "/pages/Recommend/Recommend",
        ComplaintList: "/pages/ComplaintList/ComplaintList",
        balance: "/pages/balance/balance",
        Recharge: "/pages/Recharge/Recharge",
        Tricycle: "/pages/Tricycle/Tricycle",
        authorizedLogin: "/pages/authorizedLogin/authorized",
        wapUrl: "/pages/wapUrl/index"
    },


    /**
     * 预览图片
     * data-index="{{index}}" data-allImg="{{imgUrls}}" catchtap="preview"
     * app.previewImage(even);
     * */
    previewImage: function (eve) {
        let $dataset = eve.currentTarget.dataset;
        let currentAllImg = $dataset.allimg;
        let $imgAttr = [];
        if (typeof currentAllImg === "string") {
            $imgAttr.push(currentAllImg)
        } else {
            $imgAttr = currentAllImg.map(function (li) {
                return li;
            });
        }
        wx.previewImage({
            current: $imgAttr[$dataset.index],
            urls: $imgAttr
        })
    },

    /**
     * 登录
     */
    login: function () {
        var _this = this;
        const wxmp = this.wxmp;
        let code = '';

        const stop = () => Promise.reject();

        wxmp.getSetting().then(res =>{

                // 用户登录
                if (res.authSetting['scope.userInfo']){
                    return wxmp.login();
                }else{
                    _this.navigateTo(_this.page.authorizedLogin);
                }
                
            }).then(res =>{

                // 请求用户信息
                if(res.code){

                    code = res.code;
                    return wxmp.getUserInfo();

                }else{
                    _this.navigateTo(_this.page.home);
                }
                
            }).then(res =>{

                // 后台登录注册
                var inviter = wx.getStorageSync('inviter');
                return _this.request({
                    url: _this.api.url.login.miniProgramLogin,
                    data: {
                        code: code,
                        rawData: res.rawData,
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        signature: res.signature,
                        inviter: inviter || 0
                    }
                })
                
            }).catch(() =>{
                _this.navigateTo(_this.page.authorizedLogin)
            }).then( res =>{

                if (res.status == 1) {
                    _this.globalData.userInfo = res.data;
                    wx.setStorageSync('user_id', res.data.user_id);
                    wx.setStorageSync('token', res.data.token);
                    wx.removeStorageSync('inviter');
                    
                    
                    
                    // 连接websocket
                    _this.socket(); 

                    // 是否有正在发布的订单
                    // _this.checkOrder()
                    

                    //获取当前页面URL
                    var pages = getCurrentPages();//获取加载的页面
                    if(pages == 0) {
                        return;
                    }

                    var currentPage = pages[pages.length-1];//获取当前页面的对象
                    var url = currentPage.route;//当前页面url
                    currentPage.onShow();

                    //跳回首页
                    if(url == _this.page.authorizedLogin){
                        _this.switchTab(_this.page.home);
                    }

                } else {
                    _this.showToast(res.msg);
                }

            })
    },

    /**
     * 是否有正在发布的订单
     */
    checkOrder: function(){
        var _this = this;
        var object = {
            url: _this.api.url.order.orderList,
            data: {status: 0},
        }

        
        return _this.request(object).then(res =>{

            if(res.status == 1) {
                if(res.data.length > 0) {
                    // 跳转到等待接单页面
                    _this.redirectTo(_this.page.SingleState, 'id='+res.data[0]['id']);
                }
            }
            
        });
        
    },

    /**
     * 请求接口
     * @param object 网络请求API【wx.request】的参数
     * @param showLoading 是否隐藏加载层
     */
    request: function (object, showLoading) {
        var _this = this;
        
        // 加载层
        if(showLoading !== false){
            _this.showLoading();
        }

        // 参数
        var data = object.data || {};
        
        // 固定参数
        data['user_id'] = wx.getStorageSync('user_id');
        data['token'] = wx.getStorageSync('token');
        
        // json序列化
        data = JSON.stringify(data);
        
        // 签名
        var apisign = _this.api.getSign(data);

        // 请求参数
        object.data = {data: data, apisign: apisign};
        
        // header
        object.header = {'content-type': 'application/x-www-form-urlencoded'};

        // 请求方式
        if(!object.method) {
            object.method = 'post';
        }
        
        // 成功回调
        var successFunc = object.success;
        
        var success = function(res) {
            if(successFunc && typeof successFunc === 'function'){
                successFunc(res);
            }
            return res;
        }
        
        object.success = success;


        // 失败回调
        var failFunc = object.fail;
        var fail = function(res) {
            if (typeof failFunc == 'function') {
                failFunc(res);
            } else {
                _this.showToast('网络请求错误', '/images/icon-warning.png');
            }
        }
        object.fail = fail;


        // complete回调
        var completeFunc = object.complete;
        var complete = function(res) {
            if(showLoading !== false){
                _this.hideLoading();
            }
            if(typeof completeFunc == 'function') {
                completeFunc(res);
            }
        }


        delete object.success;
        delete object.fail;
        
        return this.wxmp.request(object).then(res =>{

            complete(res)
            
            if(res.statusCode === 200){

                // 登录校验
                if(res.data.status === -1){
                    _this.login()
                }
                
                return res.data

            }else{
                return Promise.reject(res)
            }
            
        }).then(success).catch(fail);
    },



    // websocket
    socket: function() {

        var _this = this;
        
        this.wxmp.connectSocket({
            url: 'wss://zhuangxiu.xjkss.com/websocket'
        })
        
        wx.onSocketOpen(function(res){
            _this.checkOrder()
        })
        
        wx.onSocketMessage(function(res){
            var data = JSON.parse(res.data);
            if(data.type == 0) {

                // 调接口绑定用户
                var object = {
                    url: _this.api.url.socket.bindUser,
                    data: {client_id: data.client_id},
                }
                _this.request(object);
                
            }
        })

        wx.onSocketClose(function(res) {

            // 重连
            wx.connectSocket({
                url: 'wss://zhuangxiu.xjkss.com/websocket'
            })

        })

    }
});